<template>
  <div class="filter-item" v-if="type === 'search'">
    <span class="filter-item-label">{{ label }}</span>
    <el-input
      size="small"
      class="filter-item-input"
      :value="value"
      :placeholder="placeholder"
      :clearable="clearable"
      @input="onSearchInputChange"
      @keyup.enter.native="enterSubmit"
    />
  </div>
  <div class="filter-item" v-else-if="type === 'enhancement'">
    <span class="filter-item-label">{{ label }}</span>
    <el-autocomplete
      size="small"
      class="filter-item-input"
      :value="value"
      :placeholder="placeholder"
      :fetch-suggestions="options"
      :clearable="clearable"
      @input="onChange"
      @select="onEnhancementChange"
    />
  </div>
  <div class="filter-item" v-else-if="type === 'select'">
    <span class="filter-item-label">{{ label }}</span>
    <el-select
      size="small"
      class="filter-item-input"
      :value="value"
      :placeholder="placeholder"
      :filterable="filterable"
      :clearable="clearable"
      @change="onChange"
    >
      <el-option
        v-for="item in options"
        :key="item.code"
        :label="item.name"
        :value="item.code"
      ></el-option>
    </el-select>
  </div>
  <!-- 动态选择, 选项从远程方法中获取 -->
  <div class="filter-item" v-else-if="type === 'dynamic-select'">
    <span class="filter-item-label">{{ label }}</span>
    <el-select
      filterable
      remote
      reserve-keyword
      size="small"
      class="filter-item-input"
      :value="value"
      :placeholder="placeholder"
      :remote-method="dynamicSelectRemoteMethod"
      :loading="isLoading"
      :clearable="clearable"
      @change="onChange"
    >
      <el-option
        v-for="item in remoteOptions"
        :key="item.code"
        :label="item.name"
        :value="item.code"
      >
      </el-option>
    </el-select>
  </div>
  <div class="filter-item" v-else-if="type === 'cascader'">
    <span class="filter-item-label">{{ label }}</span>
    <el-cascader
      size="small"
      class="filter-item-input"
      :value="value"
      :show-all-levels="false"
      :props="cascaderProps"
      :options="options"
      :placeholder="placeholder"
      :clearable="clearable"
      @change="onChange"
    >
    </el-cascader>
  </div>
  <div class="filter-item" v-else-if="type === 'cascader-plus'">
    <span class="filter-item-label">{{ label }}</span>
    <el-cascader
      size="small"
      class="filter-item-input"
      :value="value"
      :show-all-levels="false"
      :props="cascaderPlusProps"
      :options="options"
      :placeholder="placeholder"
      :clearable="clearable"
      @change="onChange"
    >
    </el-cascader>
  </div>
  <div class="filter-item" v-else-if="type === 'multi-select'">
    <span class="filter-item-label">{{ label }}</span>
    <el-select
      multiple
      size="small"
      class="filter-item-input"
      collapse-tags
      :value="value"
      :placeholder="placeholder"
      :clearable="clearable"
      @change="onChange"
    >
      <el-option
        v-for="item in options"
        :key="item.code"
        :label="item.name"
        :value="item.code"
      ></el-option>
    </el-select>
  </div>
  <!-- 市级城市选择 -->
  <!-- <div class="filter-item" v-else-if="isAreaCascaderComp">
    <span class="filter-item-label">{{ label }}</span>
    <el-cascader
      size="small"
      class="filter-item-input"
      :filterable="this.extraOptions.filterable || false"
      :props="cityProps"
      :value="value"
      :disabled="isLoading"
      :options="areaOptions"
      :placeholder="placeholder"
      :clearable="clearable"
      @change="onChange"
    ></el-cascader>
  </div> -->
  <div class="filter-item" v-else-if="type === 'date' || type === 'time'">
    <span class="filter-item-label">{{ label }}</span>
    <el-date-picker
      v-model="value"
      type="daterange"
      size="small"
      align="right"
      value-format="yyyy-MM-dd"
      format="yyyy/MM/dd"
      unlink-panels
      range-separator="至"
      :start-placeholder="leftText"
      :end-placeholder="rightText"
      :picker-options="pickerOptions"
      @change="onDateChange"
    >
    </el-date-picker>
  </div>
  <div class="filter-item" v-else-if="type === 'dateTime'">
    <span class="filter-item-label">{{ label }}</span>
    <el-date-picker
      v-model="value"
      type="datetimerange"
      size="small"
      align="right"
      format="yyyy/MM/dd HH:mm:ss"
      value-format="yyyy-MM-dd HH:mm:ss"
      unlink-panels
      range-separator="至"
      :start-placeholder="leftText"
      :end-placeholder="rightText"
      :picker-options="pickerOptions"
      @change="onChange"
    >
    </el-date-picker>
  </div>
  <!-- 车辆品牌/车系-->
<!--  <div class="filter-item" v-else-if="type === 'carModel'">
    <span class="filter-item-label">{{ label }}</span>
    <el-cascader
      v-model="value"
      size="small"
      class="filter-item-input"
      filterable="true"
      :props="carModelProps"
      :options="carModelOptions"
      :placeholder="placeholder"
      :clearable="clearable"
      @visible-change="carModelVisibleChange"
      @change="onChange"
    ></el-cascader>
  </div> -->
  <!-- 所属战区 -->
<!--  <div class="filter-item" v-else-if="type === 'zoneModel'">
    <span class="filter-item-label">{{ label }}</span>
    <el-cascader
      v-model="value"
      size="small"
      class="filter-item-input"
      filterable="true"
      :props="zoneModelProps"
      :options="zoneModelOptions"
      :placeholder="placeholder"
      :clearable="clearable"
      @visible-change="zoneModelVisibleChange"
      @change="onChange"
    ></el-cascader>
  </div> -->
  <!-- 区间过滤 -->
  <div class="filter-item" v-else-if="type === 'section'">
    <span class="filter-item-label">{{ label }}</span>
    <section-box 
    v-model="value" 
    :minValue="extraOptions.minValue"
    :maxValue="extraOptions.maxValue"
    :minPlacehoder="extraOptions.minPlaceholder" 
    :maxPlacehoder="extraOptions.maxPlaceholder" 
    @change="onChange"></section-box>
  </div>
</template>

<script>
import sectionBox from './sectionBox';
// import * as AreaService from '../../api/area';
// import MemoryCache from '../../utils/memory-cache';
// import * as AreaFormator from '../../utils/area-formator';
// import { firstLetter, byBrand, bySeries } from '../../api/car-brand-series';
// import { listZoneTree } from '../../api/basic-series';

export default {
  name: 'FilterItem',
  components: {
    sectionBox
  },
  props: {
    value: {
      type: [String, Number,Array],
      default: '',
    },
    type: {
      type: String,
      default: 'select',
    },
    label: {
      type: String,
      default: '',
    },
    // 是否可搜索
    filterable: {
      type: Boolean,
      default: false,
    },
    // 是否可清空
    clearable: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请筛选',
    },
    leftText: {
      type: String,
      default: '开始日期',
    },
    rightText: {
      type: String,
      default: '结束日期',
    },
    options: {
      type: [Array, Function],
      default() {
        return [];
      },
    },
    extraOptions: {
      type: Object,
      default() {
        return {};
      },
    },
    pickerOptions: {
      type: Object,
      default() {
        return {
          // 快捷时间选项
          shortcuts: [
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              },
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              },
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              },
            },
          ],
        };
      },
    },
    event: {
      type: String,
    },
  },
  computed: {
    // isAreaCascaderComp() {
    //   return ['province', 'city', 'area'].includes(this.type);
    // },
  },
  data() {
    var _this = this;
    return {
      // 部分筛选项数据可能需要从远端拉取数据, 此时需要加载
      isLoading: false,
      // 城市选择器配置
      cityProps: {
        value: 'code',
        label: 'name',
        emitPath: false,
        checkStrictly: this.extraOptions.checkStrictly || false,
      },
      cascaderProps: {
        value: 'code',
        label: 'name',
        emitPath: false,
      },
      cascaderPlusProps: {
        value: this.extraOptions.valueText || 'code',
        label: this.extraOptions.labelText || 'name',
        emitPath: false,
        checkStrictly: true,
      },
      areaOptions: [],
      remoteOptions: [],
      // carModelOptions: [],
      // carModelProps: {
      //   lazy: true,
      //   checkStrictly: this.extraOptions.checkStrictly ? true : false,
      //   multiple: this.extraOptions.multiple ? true : false,
      //   value: 'id',
      //   label: 'name',
      //   async lazyLoad(node, resolve) {
      //     let nodeData = [];
      //     nodeData = await _this.getNodesData(node);
      //     resolve(nodeData);
      //   },
      // },
      // zoneModelOptions: [],
      // zoneModelProps: {
      //   lazy: false,
      //   checkStrictly: true,
      //   multiple: false,
      //   emitPath: false,
      //   value: 'id',
      //   label: 'title',
      // },
    };
  },
  methods: {
    enterSubmit() {
      console.log('即将进行快速提交 ==>')
      this.value && this.$emit('submit');
    },
    // 所属战区
    // async zoneModelVisibleChange() {
    //   if (['zoneModel'].includes(this.type)) {
    //     if (this.zoneModelOptions && this.zoneModelOptions.length === 0) {
    //       let { data, code } = await listZoneTree();
    //       if (code === 200) {
    //         this.zoneModelOptions = data;
    //       }
    //     }
    //   }
    // },
    // 如果是车辆品牌/车系
    // carModelVisibleChange() {
    //   if (['carModel'].includes(this.type)) {
    //     this.carModelOptions &&
    //       this.carModelOptions.length === 0 &&
    //       this.firstLetter();
    //   }
    // },
    onEnhancementChange(e) {
      this.onChange(e.value);
    },
    onSearchInputChange(e) {
      console.log('快速搜索框输入变化 ==>', e);
      this.onChange(e.trim());
    },
    onChange(e) {
      console.log('Filter内容变化 ==>', e);
      if (this.event) {
        this.$emit('filter-select', {
          event: this.event,
          data: e,
        });
      }
      this.$emit('input', e);
    },
    onDateChange(e) {
      console.log('检测到onDateChange ==>', e);
      if (!e || !e.length) {
        this.onChange('');
        return;
      }
      if (this.type === 'date') {
        this.onChange([`${e[0]} 00:00:00`, `${e[1]} 23:59:59`]);
      } else {
        this.onChange([`${e[0]} 00:00:00`, `${e[1]} 23:59:59`]);
      }
    },
    // async initAreaData() {
    //   this.isLoading = true;
    //   this.areaOptions = await AreaFormator.fetchAreaListAndSave(this.type);
    //   console.log('当前城市选项 ==>', this.areaOptions);
    //   this.isLoading = false;
    // },
    dynamicSelectRemoteMethod(query) {
      this.isLoading = true;
      this.options(query, options => {
        this.isLoading = false;
        this.remoteOptions = options;
      });
    },
    async firstLetter() {
      let { data } = await firstLetter();
      if (typeof data === 'object') {
        let carModelOptions = [];
        Object.keys(data).forEach(key => {
          carModelOptions = carModelOptions.concat(data[key]);
        });
        if (!this.extraOptions.level || this.extraOptions.level === 1) {
          carModelOptions = carModelOptions.map(item => {
            if (!this.extraOptions.level || this.extraOptions.level === 1) {
              item.leaf = true;
            }
            return item;
          });
        }
        this.carModelOptions = carModelOptions;
      }
    },
    async getNodesData({ level, data: nodeData }) {
        let nodes = [];
        if (level === 1 && this.extraOptions.level > 1) {
          let { data } = await byBrand(nodeData.id);
          nodes = data || [];
          if (this.extraOptions.level === 2) {
            nodes.map(item => {
              item.leaf = true;
              return item;
            });
          }
        } else if (level === 2 && this.extraOptions.level > 2) {
          let { data } = await bySeries(nodeData.id);
          Object.keys(data).forEach(key => {
            nodes = nodes.concat(data[key]);
          });
          nodes = nodes.map(item => {
            item.leaf = true;
            return item;
          });
        }
        return Promise.resolve(nodes);
    },
  },
  mounted() {
    // 如果是区域选择类, 需要初始化区域信息
    // if (['city', 'province', 'area'].includes(this.type)) {
    //   this.initAreaData();
    // }
  },
};
</script>

<style scoped lang="less">
@import '../style/config';

.filter-item {
  height: 32px;
  margin-right: 15px;
  margin-bottom: 15px;
  .flexible(row, center, flex-start);

  &-label {
    font-family: PingFangSC-Regular;
    font-size: 12px;
    font-weight: 400;
    color: #a0a0a0;
    line-height: 14px;
    margin-right: 5px;
  }

  &-input {
    width: 200px;
  }
}
</style>
